﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 资产维护登记
    /// </summary>
    [ControllerGroup(groupName: "AssetUpkeep", useage: "资产管理-维护登记")]
    public class AssetUpkeepController : BaseController
    {
        private JWTPlayloadInfo playload;
        private readonly AssetUpkeepBll _instance = AssetUpkeepBll.Instance;

        /// <summary>
        /// 维护登记分页查询
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="number">维护编号</param>
        /// <param name="assetNo">资产编号</param>
        /// <param name="assetName">资产名称</param>
        /// <param name="status">状态（0：审批中；1：已完成）</param>
        /// <param name="date">维护时间</param>
        /// <param name="person">维护人员</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageIndex = 1, int pageSize = 10, string number = "", string assetNo = "", string assetName = "",
             int status = -1, string date = "", string person = "")
        {
            var strWhere = new StringBuilder("");
            if (!string.IsNullOrEmpty(number))
            {
                strWhere.Append($" and t1.AU_Number like '%{number}%'");
            }
            if (!string.IsNullOrEmpty(assetNo))
            {
                strWhere.Append($" and t2.AU_AssetNo like '%{assetNo}%'");
            }
            if (!string.IsNullOrEmpty(assetName))
            {
                strWhere.Append($" and t2.AU_AssetName like '%{assetName}%'");
            }
            if (!string.IsNullOrEmpty(person))
            {
                strWhere.Append($" and t1.AU_Person like '%{person}%'");
            }
            if (status != -1)
            {
                strWhere.Append($" and t1.AU_Status = {status}");
            }
            if (!string.IsNullOrEmpty(date))
            {
                // 判断是否是日期格式
                if (DateTime.TryParse(date, out DateTime parsedDate))
                {
                    strWhere.Append($" and t1.AU_Date = '{date}'");
                }
                else
                {
                    return JsonHelper.ErrorJson("无效的日期格式");
                }
            }

            var dt = _instance.GetPageList(pageSize, pageIndex, strWhere.ToString(), "t1.AU_Date DESC", out int records);
            var totalPages = PageHelper.GetPageCount(pageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 根据ID获取实体对象
        /// </summary>
        /// <param name="ID">数据表ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModel(int ID)
        {
            if (ID > 0)
            {
                var model = _instance.GetModelById(ID);
                if (model != null)
                {
                    // 查询文件
                    var dt = UploadBll.Instance.GetFiles(ID, "AssetUpkeep");
                    model.FileList = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 查询维护资产（新增用）
        /// </summary>
        /// <param name="assetNo"></param>
        /// <param name="assetName"></param>
        /// <param name="assetStatus"></param>
        /// <returns></returns>
        public HttpResponseMessage GetKeepAsset(string assetNo = "", string assetName = "", int assetStatus = -1)
        {
            var strWhere = new StringBuilder("");
            if (!string.IsNullOrEmpty(assetNo))
            {
                strWhere.Append($" and t1.AssetNo like '%{assetNo}%'");
            }
            if (!string.IsNullOrEmpty(assetName))
            {
                strWhere.Append($" and t1.AssetName like '%{assetName}%'");
            }

            if (assetStatus != -1)
            {
                strWhere.Append($" and t2.AssetStatus = {assetStatus}");
            }

            var dt = _instance.GetKeepAsset(strWhere.ToString());

            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt));
        }

        /// <summary>
        /// 查看详情
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="assetNo">资产编号</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetDetail(int id, string assetNo)
        {
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            if (string.IsNullOrEmpty(assetNo))
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            var dt = _instance.GetDetail(id, assetNo);

            var model = CommonOperation.DataTableToModel<AssetUpkeep>(dt);
            if (model != null)
            {
                // 查询文件
                var filedt = UploadBll.Instance.GetFiles(id, "AssetUpkeep");
                model.FileList = CommonOperation.ConvertDataTableToModelList<FileData>(filedt);
            }
            return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
        }

        /// <summary>
        /// 新增维护登记
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddAssetUpkeep([FromBody] AssetUpkeepHead model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                var msg = "";
                var isOk = _instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    var res = _instance.AddAssetUpkeep(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.FileList != null && model.FileList.Count > 0)
                        {
                            UploadBll.Instance.Update(model.ID, model.FileList);
                        }


                        LogHelper.LogAction(playload, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Add, "新增维护登记");
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Add, "新增维护登记");
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Add, "新增维护登记");
                throw;
            }
        }

        /// <summary>
        /// 撤销维护登记
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="assetNo">资产编号</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage Revoke(int id, string assetNo)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (id <= 0)
                {
                    return JsonHelper.FailJson("参数错误！");
                }
                else
                {
                    // 判断状态（状态为0：审批中才可删除）
                    if (!_instance.IsExist(" and ID=" + id + " and AU_Status=0 "))
                    {
                        return JsonHelper.FailJson("该数据已审批完成，不能撤销！");
                    }
                    else
                    {
                        var result = false;

                        result = _instance.Revoke(id, assetNo, out string msg);
                        if (result)
                        {
                            // 更新维护提醒表中状态为 ‘3：处理中’
                            AssetKeepWarnBll.Instance.AfterDelete(id, assetNo);
                            LogHelper.LogAction(playload, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Delete, $"撤销维护登记,ID:{id},资产编号：{assetNo}");
                            return JsonHelper.SuccessJson(msg);
                        }
                        else
                        {
                            LogHelper.LogWarn(playload, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Delete, $"撤销维护登记,ID:{id},资产编号：{assetNo}");
                            return JsonHelper.SuccessJson(msg);
                        }


                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Delete, $"撤销维护登记,ID:{id},资产编号：{assetNo}");
                throw;
            }
        }

        #region 上传文件相关

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage UploadFile()
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];

            var list = new List<FileData>();
            var files = HttpContext.Current.Request.Files;
            foreach (var key in files.AllKeys)
            {
                HttpPostedFile postedFile = files[key];
                if (!string.IsNullOrEmpty(postedFile.FileName))
                {
                    // file.SaveAs(HttpContext.Current.Server.MapPath("~/imgcoll/") + file.FileName);
                    //文件扩展名，不含“.”
                    string fileExt = Utils.GetFileExt(postedFile.FileName);

                    // 文件类型
                    Regex regex = new Regex(@"gif|jpg|jpeg|png|bmp|webp");
                    var isMatch = regex.IsMatch(fileExt);
                    if (!isMatch)
                    {
                        return JsonHelper.ErrorJson("文件类型不匹配");
                    }

                    FileData model = UploadHelper.SaveFilePic(postedFile, UploadHelper.uploadPath + "files/pc/asset/keep/" + DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMddHHmmss"));

                    // 文件类型
                    model.FileType = fileExt;

                    // 关联表
                    model.RelationTable = "AssetUpkeep";

                    if (model != null)
                    {
                        list.Add(model);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (list.Count > 0)
            {
                var result = UploadBll.Instance.AddList(list);
                if (result)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Upload, "上传文件");
                    return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Upload, "上传文件");
                    return JsonHelper.ErrorJson("上传失败，稍后重试");
                }
            }
            else
            {
                return JsonHelper.ErrorJson("没有匹配的文件类型");
            }
        }

        /// <summary>
        /// 根据文件ID删除文件
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePic(string fileID)
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (string.IsNullOrEmpty(fileID))
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            FileData model = UploadBll.Instance.GetFileByID(fileID);
            if (model != null)
            {
                bool res = UploadBll.Instance.DeleteFilesByID(fileID, model);
                if (res)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Delete, "删除文件(ID:" + fileID + ")");
                    return JsonHelper.SuccessJson("删除成功！");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.AssetUpKeep, Constant.ActionEnum.Delete, "删除文件(ID:" + fileID + ")");
                    return JsonHelper.FailJson("删除失败！");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误！,文件不存在");
            }
        }

        #endregion 上传文件相关

    }
}
